/**
* Copyright (c) 2015-2016 VisionStar Information Technology (Shanghai) Co., Ltd. All Rights Reserved.
* EasyAR is the registered trademark or trademark of VisionStar Information Technology (Shanghai) Co., Ltd in China
* and other countries for the augmented reality technology developed by VisionStar Information Technology (Shanghai) Co., Ltd.
*/

#include <jni.h>
#include <GLES2/gl2.h>
#include "NativeImplement.h"
#include "MagicFinger.h"
#include <android/log.h>
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "keymatch", __VA_ARGS__)

namespace EasyAR {
    namespace magicfinger {

        MagicFinger::MagicFinger()
        {
            view_size[0] = -1;
            tracked_target = 0;
            active_target = 0;
            for(int i = 0; i < image_number; ++i) {
                texid[i] = 0;
                renderer[i] = new VideoRenderer;
            }
            video = NULL;
            video_renderer = NULL;
        }

        MagicFinger::~MagicFinger()
        {
            for(int i = 0; i < image_number; ++i) {
                delete renderer[i];
            }
        }

        void MagicFinger::initGL()
        {
            augmenter_ = Augmenter();
            for(int i = 0; i < image_number; ++i) {
                renderer[i]->init();
                texid[i] = renderer[i]->texId();
            }
        }

        void MagicFinger::resizeGL(int width, int height)
        {
            view_size = Vec2I(width, height);
        }

        void MagicFinger::render()
        {
            glClearColor(0.f, 0.f, 0.f, 1.f);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            Frame frame = augmenter_.newFrame(tracker_);
            if(view_size[0] > 0){
                AR::resizeGL(view_size[0], view_size[1]);
                if(camera_ && camera_.isOpened())
                    view_size[0] = -1;
            }
            augmenter_.drawVideoBackground();

            AugmentedTarget::Status status = frame.targets()[0].status();
            if(status == AugmentedTarget::kTargetStatusTracked){
                int id = frame.targets()[0].target().id();
                if(active_target && active_target != id) {
                    video->onLost();
                    delete video;
                    video = NULL;
                    tracked_target = 0;
                    active_target = 0;
                }
                if (!tracked_target) {
                    if (video == NULL) {

                        for (int i = 0; i < image_number; ++i) {

                            if(frame.targets()[0].target().name() == std::string(pic_name[i]) && texid[i]) {

                                video = new ARVideo;
                                video->openVideoFile(video_name[i], texid[i]);
                                video_renderer = renderer[i];
                                break;
                            }
                        }
                    }
                    if (video) {
                        video->onFound();
                        tracked_target = id;
                        active_target = id;

                        recognizedPic(id);
                        LOGD("tracked id and active id %d", id);
                    }
                }
                Matrix44F projectionMatrix = getProjectionGL(camera_.cameraCalibration(), 0.2f, 500.f);
                Matrix44F cameraview = getPoseGL(frame.targets()[0].pose());
                ImageTarget target = frame.targets()[0].target().cast_dynamic<ImageTarget>();
                if(tracked_target) {
                    video->update();
                    video_renderer->render(projectionMatrix, cameraview, target.size());
                }
            } else {

                recognizedPic(-1);
                if (tracked_target) {
                    video->onLost();
                    tracked_target = 0;
                }
            }
        }

        bool MagicFinger::clear()
        {
            AR::clear();
            if(video){
                delete video;
                video = NULL;
                tracked_target = 0;
                active_target = 0;
            }
            return true;
        }

        void MagicFinger::recognizedPic(int i)
        {
            JNIEnv * jniEnv;
            int status = javaVM->GetEnv( (void * *) &jniEnv, JNI_VERSION_1_6);
//            LOGD("javaVM->GetEnv status : %d", status);

            jclass javaClass = jniEnv->FindClass("yixingren/magicfinger/MainActivity");
//            jfieldID javavId = jniEnv->GetFieldID(javaClass, "var_name", "Ljava/lang/String;");
            jmethodID jMethodID = jniEnv->GetStaticMethodID(javaClass, "recognizedPic", "(I)V");
            if ( jMethodID){

                jniEnv->CallStaticVoidMethod(javaClass, jMethodID, i);
            }
            else
            {
//                PRINT_ERROR("invokeJavaOc getDistance error");
            }
        }
    }
}
